package android_serialport_api;

import com.hzvdvmc.autosale.MyApp;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.seriaport.SeriaCmdRequestManager;
import com.hzvdvmc.autosale.seriaport.SerialCmdEnum;
import com.hzvdvmc.autosale.seriaport.SerialCmdResponseManager;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.StringUtil;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android_serialport_api.SerialPort;

/**
 * Created by william on 2017/12/24.
 */

public class SeriaPortClient {
    public static String DEV_A = "/dev/ttyS0";
    public static String DEV_B = "/dev/ttyS1";
    public static String DEV_C = "/dev/ttyS2";
    public static String DEV_D = "/dev/ttyS3";
//    public static final int DEFAULT_BAUDRATE = 115200; //默认波特率
    public static final int DEFAULT_BAUDRATE = 9600; //默认波特率
    private SerialPort mSeriPort;
    private InputStream in;
    private OutputStream out;
    private ReceivedThread mRecivedThread;
    private String filePath;
    private Timer timer = new Timer();
    private TimerTask task;
    private StringBuffer sb;

    public SeriaPortClient(String filePath) {
        this.filePath = filePath;
        initSerial();
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    /**
     * 打开串口
     */
    public void initSerial() {
        try {
            LogUtil.p("serialport is init..." + filePath);
//            int baudrate = SPUtils.getInstance().getInt(SpKey.BO_RATE, DEFAULT_BAUDRATE);
            mSeriPort = new SerialPort(new File(filePath), DEFAULT_BAUDRATE, 0);
            in = mSeriPort.getInputStream();
            out = mSeriPort.getOutputStream();

            mRecivedThread = new ReceivedThread();
            mRecivedThread.start();

            startHeartBeat();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startHeartBeat() {
        task = new TimerTask() {
            @Override
            public void run() {
                String fullCmd = SeriaCmdRequestManager.getFullCommand(SerialCmdEnum.HEARTBEAT, getAddressCode());
                write(StringUtil.hexStringToBytes(fullCmd));
            }
        };
        timer.schedule(task, TimeConstant.SERIAL_HEART, TimeConstant.SERIAL_HEART);

    }

    public void stopHeartBeat() {
        if (task != null) {
            task.cancel();
        }
    }


    private String getAddressCode() {
        if (DEV_A.equals(filePath)) {
            return "00";
        }
        if (DEV_B.equals(filePath)) {
            return "01";
        }
        if (DEV_C.equals(filePath)) {
            return "02";
        }
        if (DEV_D.equals(filePath)) {
            return "03";
        }
        return "";
    }
//
//
//    public boolean isConnected() {
//        if (mSeriPort == null) {
//            return false;
//        }
//        return mSeriPort.isConnected();
//    }


    public void close() {
        if (mSeriPort != null) {
            mSeriPort.close();
        }
    }

    /**
     * 串口发送字节
     */

    public void write(byte[] bytes) {
        try {
            out.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 串口接收线程
     */
    private class ReceivedThread extends Thread {

        @Override
        public void run() {
            super.run();

            while (!isInterrupted()) {
                int length;
                try {
                    byte[] buffer = new byte[64];
                    if (in == null) return;
                    length = in.read(buffer);
                    byte[] byteData = Arrays.copyOf(buffer, length);
                    if (length > 0) {
                        String cmd = StringUtil.bytesToHexString(byteData);
//                        LogUtil.i("SerialPortClient", "{SeriaPortClient} received cmd=" + cmd);
                        if (cmd.startsWith(SerialCmdEnum.START.getValue())) {
                            if (sb==null){
                                sb = new StringBuffer();
                            }
                        }
                        sb.append(cmd);
                        if (cmd.endsWith(SerialCmdEnum.END.getValue())) {
                            LogUtil.i("SerialPortClient", "{SeriaPortClient} final cmd=" + sb.toString());
                            String[] ees = sb.toString().split("ee");
                            SerialCmdResponseManager.getInstance().handleResponse(ees[0]);
                            sb = null;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
